<template>
    <!-- 左侧菜单栏 -->
    <div class="left-menu">
        <!-- 实体类 -->
        <div class="entity-types">
            <div class="head-img">
                <el-icon style="float: left;" :size="20">
                    <Avatar />
                </el-icon>
                <div>实体类</div>
            </div>
            <div class="button">
                <button @click="downloadSampleDefinition">定义样例</button>
                <button @click="triggerFileUpload">导入定义</button>
                <input type="file" ref="fileInput" @change="handleFileUpload" accept=".xlsx" style="display: none;" />
            </div>
            <div class="entity-type-list">
                <div v-for="entity in entities" :key="entity.id" class="entity-type-item"
                    :style="{ 'background-color': editorStore.getEntityColor(entity.id) }">
                    <div class="entity-info">
                        <span>{{ entity.text }}</span>
                        <span v-if="entity.markedCount !== undefined" class="entity-marked-count">{{ entity.markedCount
                            }}个</span>
                    </div>
                    <div class="entity-actions">
                        <button @click="editEntity(entity)" title="编辑实体类">✏️</button>
                        <button @click="deleteEntity(entity)" title="删除实体类">🗑️</button>
                    </div>
                </div>
            </div>
            <div class="button">
                <button @click="showAddEntityDialog" title="添加实体类">添加实体类</button>
                <button @click="exportDefinition" title="导出Excel格式的实体定义文件 (.xlsx)">导出定义</button>
            </div>
        </div>
        <!-- 实体实例列表 -->
        <div class="entity-instances">
            <div class="head-img">
                <el-icon style="float: left;" :size="20">
                    <UserFilled />
                </el-icon>
                <div>实体实例</div>
            </div>
            <div v-for="entity in entities" :key="entity.id" class="entity-instance-container">
                <div class="entity-instance-title">{{ entity.text }}</div>
                <div class="entity-instance-boxes">
                    <template v-if="getEntityInstances(entity.id).length > 0">
                        <div v-for="(instance, index) in getEntityInstances(entity.id)" :key="index"
                            class="entity-instance-item"
                            :style="{ backgroundColor: editorStore.getEntityColor(entity.id) }"
                            style="position: relative;">
                            <div class="entity-instance-content">{{ instance.text }}</div>
                            <div v-if="!instance.isChecked" class="unchecked-indicator"></div>
                            <div class="entity-check-status">
                                <span v-if="!instance.isChecked">未检1处</span>
                                <span v-else>已检1处</span>
                            </div>
                        </div>
                    </template>
                    <div v-if="getEntityInstances(entity.id).length === 0" class="entity-instance-item empty-instance"
                        :style="{ backgroundColor: editorStore.getEntityColor(entity.id) }">
                        <div class="entity-instance-content">暂无标注</div>
                    </div>
                </div>
                <div class="entity-instance-status">
                    <span>已标注 {{ getEntityInstances(entity.id).length }} 处</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑弹出框 -->
    <div v-if="dialogVisible" class="dialog">
        <div class="dialog-content">
            <h3>编辑实体定义</h3>
            <label>ID: <input type="text" v-model="currentEntity.id" disabled></label>
            <label>名称: <input type="text" v-model="currentEntity.text"></label>
            <label>描述: <input type="text" v-model="currentEntity.description"></label>
            <label>路径: <input type="text" v-model="currentEntity.path"></label>
            <label style="align-items: flex-start;">属性:
                <div style="flex: 1;">
                    <div v-for="(property, index) in currentEntity.propertiesList" :key="index" class="property-item">
                        <input v-model="property.key" type="text" placeholder="属性名" />
                        <select v-model="property.type">
                            <option value="text">文本</option>
                            <option value="number">数字</option>
                            <option value="boolean">布尔值</option>
                            <option value="array">数组</option>
                            <option value="object">对象</option>
                        </select>
                        <input v-model="property.description" type="text" placeholder="描述" />
                        <button type="button" @click="removeProperty(index)" class="remove-button">删除</button>
                    </div>
                    <button type="button" @click="addProperty" class="attribute-button">添加属性</button>
                </div>
            </label>
            <div class="dialog-footer">
                <button @click="dialogVisible = false">取消</button>
                <button @click="saveEntity">确定</button>
            </div>
        </div>
    </div>
    <!-- 删除确认弹出框 -->
    <div v-if="deleteDialogVisible" class="dialog">
        <div class="dialog-content-delete">
            <h3>删除实体类</h3>
            <p>确定要删除实体类 "{{ entityToDelete?.text }}" 吗？</p>
            <div class="dialog-footer">
                <button @click="deleteDialogVisible = false">取消</button>
                <button @click="confirmDelete">确定</button>
            </div>
        </div>
    </div>
    <!-- 添加实体类对话框 -->
    <AddEntityDialog v-model="addEntityDialogVisible" @confirm="handleAddEntity" />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { Avatar, UserFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import * as XLSX from 'xlsx';
import AddEntityDialog from './AddEntityDialog.vue';
import { useEditorStore } from '@/store/editor';
import axios from '@/plugins/axios';
import { getEntityInstances as fetchEntityInstances } from '@/api/entityApi';
import { debounce } from 'lodash';

const fileInput = ref(null);
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const entityToDelete = ref(null);
const currentEntity = ref({
    id: '',
    text: '',
    description: '',
    path: '',
    propertiesList: []
});
const entities = ref([]);
const addEntityDialogVisible = ref(false);
const editorStore = useEditorStore();

// 直接存储实体实例数据
const rawEntityInstances = ref([]);

// 在组件初始化时设置全局变量
// 设置全局方法，供TinyMCE编辑器调用更新标记数量
window.updateEntityMarkedCount = updateEntityMarkedCount;
// 设置全局实体列表，供TinyMCE编辑器使用
window.entities = entities.value;

// 添加一个加载中标志
const isLoadingInstances = ref(false);

// 创建一个防抖的加载函数
const debouncedLoadInstances = debounce(async () => {
    if (isLoadingInstances.value) return;

    await loadEntityInstancesFromDatabase();
}, 300); // 300ms 延迟

// 从数据库加载实体类
function loadEntitiesFromDatabase() {
    // 从 editorStore 获取文档 ID
    const documentId = editorStore.documentInfo?.id;

    if (!documentId) {
        console.log('未找到文档ID，无法从数据库加载实体类');
        return;
    }

    // 显示加载提示
    const loadingEntityClass = ElLoading.service({ fullscreen: true, text: '正在从数据库加载实体类...' });

    // 发送请求到后端获取实体类
    axios.get(`/get_entity_classes/${documentId}`)
        .then(response => {
            loadingEntityClass.close();
            if (response.data.code === 200 && response.data.data && Array.isArray(response.data.data)) {
                const databaseEntities = response.data.data;

                if (databaseEntities.length === 0) {
                    console.log('数据库中没有实体类数据');
                    return;
                }

                // 转换数据格式并添加颜色
                const formattedEntities = databaseEntities.map(entity => {
                    // 从 editorStore 获取已存储的颜色或生成新颜色
                    const backgroundColor = editorStore.getEntityColor(entity.id);

                    return {
                        id: entity.id,
                        text: entity.name,
                        description: entity.description,
                        path: entity.path,
                        properties: entity.attribute,
                        style: { 'background-color': backgroundColor },
                        markedCount: 0
                    };
                });

                // 更新 store 中的实体类数据
                editorStore.setEntityClasses(formattedEntities);
                // 更新本地实体列表
                entities.value = formattedEntities;

                // 加载完实体类后立即更新显示计数
                updateEntityMarkedCount();

                ElMessage.success(`从数据库加载了 ${formattedEntities.length} 个实体类`);
            } else {
                console.log('从数据库加载实体类失败:', response.data.message || '未知错误');
            }
        })
        .catch(error => {
            loadingEntityClass.close();
            console.error('从数据库加载实体类时出错:', error);
        });
}

// 显示添加实体对话框
function showAddEntityDialog() {
    addEntityDialogVisible.value = true;
}

// 修改更新实体标记数量方法，简化它的实现
function updateEntityMarkedCount(entityCounts = {}, entityTexts = {}, checkedStatus = {}) {
    console.log('更新实体标记数量', entityCounts, entityTexts);

    // 触发实体实例更新在编辑器中已完成，此处只需更新UI显示
    // 创建一个新数组来存储更新后的实体，以确保Vue能够检测到变化
    const updatedEntities = entities.value.map(entity => {
        if (!entity || !entity.id) {
            console.warn('发现无效的实体对象:', entity);
            return entity; // 返回原实体，避免处理无效数据
        }

        const updatedEntity = { ...entity };

        // 获取该实体类的所有实例数量
        const instances = getEntityInstances(entity.id) || [];
        const instanceCount = instances.length;

        // 安全地访问entityCounts
        const entityCount = entityCounts && typeof entityCounts === 'object' ? entityCounts[entity.id] : undefined;

        // 优先使用entityCounts提供的计数（可能是最新的）
        updatedEntity.markedCount = entityCount !== undefined ? entityCount : instanceCount || 0;

        // 设置总数
        updatedEntity.totalCount = updatedEntity.markedCount;

        return updatedEntity;
    });

    // 替换整个数组以确保Vue能够检测到变化
    entities.value = updatedEntities;
    // 更新全局实体列表，确保TinyMCE编辑器使用最新数据
    window.entities = entities.value;

    // 确保editorStore中的实体类数据也更新了markedCount
    editorStore.updateEntityClassesMarkCounts(updatedEntities);
}

// 添加getEntityInstances方法，用于获取特定实体类的所有实例
function getEntityInstances(entityId) {
    if (!rawEntityInstances.value) return [];

    // 直接从本地存储的实体实例数据中筛选
    return rawEntityInstances.value.filter(instance =>
        instance && instance.entityId === entityId
    );
}

// 组件挂载时从数据库加载实体类
onMounted(async () => {
    // 先加载实体类数据
    await loadEntitiesFromDatabase();

    // 再加载实体实例数据
    await loadEntityInstancesFromDatabase();

    // 添加调试代码
    console.log('原始实体实例数据:', rawEntityInstances.value);

    // 显示每个实体类的实例数量
    entities.value.forEach(entity => {
        const instances = getEntityInstances(entity.id);
        console.log(`实体类 ${entity.text} (${entity.id}) 的实例数量: ${instances.length}`);
    });

    // 确保UI更新
    updateEntityMarkedCount();
});

// 从数据库加载实体实例数据
async function loadEntityInstancesFromDatabase() {
    // 获取文档ID
    const documentId = editorStore.documentInfo?.id;
    if (!documentId) {
        console.warn('未找到文档ID，无法加载实体实例数据');
        return;
    }

    // 如果已经在加载中，直接返回
    if (isLoadingInstances.value) return;
    isLoadingInstances.value = true;

    // 显示加载提示
    const loadingInstance = ElLoading.service({
        fullscreen: true,
        text: '正在加载实体实例数据...'
    });

    try {
        // 使用API函数发送请求
        const response = await fetchEntityInstances(documentId);
        loadingInstance.close();

        console.log('完整实体实例响应:', response.data);

        // 改进数据解析，适应可能的不同响应格式
        let instancesData = [];
        if (response.data.code === 200) {
            if (response.data.data.entity_instances && Array.isArray(response.data.data.entity_instances)) {
                instancesData = response.data.data.entity_instances;
            } else if (Array.isArray(response.data.data)) {
                instancesData = response.data.data;
            }

            if (instancesData.length === 0) {
                console.log('没有找到实体实例数据');
                rawEntityInstances.value = [];
                isLoadingInstances.value = false;
                return;
            }

            // 处理实体实例数据，格式化并确保字段一致
            const processedInstances = instancesData.map(instance => {
                // 通过entity_id获取对应实体类的颜色
                const backgroundColor = editorStore.getEntityColor(instance.entity_id);
                return {
                    id: instance.id,
                    entityId: instance.entity_id,
                    documentId: instance.document_id,
                    text: instance.text,
                    isChecked: instance.is_checked !== false,
                    style: { 'background-color': backgroundColor }
                };
            });

            // 直接设置本地实体实例数据
            rawEntityInstances.value = processedInstances;

            // 同时更新editorStore中的数据，保持状态一致
            editorStore.setEntityInstances(processedInstances);
            updateEntityMarkedCount();

            console.log('实体实例数据加载完成，共', processedInstances.length, '条');
        } else {
            console.warn('加载实体实例数据失败:', response.data.message);
            // 注意这里不要清空现有数据
        }
    } catch (error) {
        loadingInstance.close();
        console.error('请求实体实例数据失败:', error);
        ElMessage.error('加载实体实例数据失败，请检查网络连接');
    } finally {
        isLoadingInstances.value = false;
        loadingInstance.close();
    }
}

// 其他函数保持不变
// ... 处理添加实体类、编辑实体类、删除实体类的方法 ...

// 处理添加实体类
function handleAddEntity(newEntity) {
    // 使用editorStore生成并保存随机颜色
    const backgroundColor = editorStore.generateRandomColor(newEntity.id);

    // 为新实体类添加CSS变量
    const entityWithColor = {
        ...newEntity,
        style: { 'background-color': backgroundColor },
        markedCount: 0 // 初始化 markedCount
    };

    // 添加到本地实体列表
    entities.value.push(entityWithColor);
    // 添加到 store 中的实体类数据
    editorStore.addEntityClass(entityWithColor);

    // 从 editorStore 获取文档 ID
    const documentId = editorStore.documentInfo?.id;

    if (!documentId) {
        ElMessage.error('实体未能保存到数据库（未找到文档ID）');
        return;
    }

    // 发送请求到后端保存实体类
    axios.post('/add_entity_class', {
        documentId: documentId,
        id: newEntity.id,
        name: newEntity.text,
        description: newEntity.description,
        path: newEntity.path,
        attribute: newEntity.properties
    })
        .then(response => {
            if (response.data.code === 200) {
                ElMessage.success('实体添加成功并已保存到数据库');
            } else {
                ElMessage.warning(`实体添加成功，但保存到数据库失败: ${response.data.message || '未知错误'}`);
            }
        })
        .catch(error => {
            console.error('保存实体类到数据库时出错:', error);
            ElMessage.warning('实体添加成功，但保存到数据库失败，请检查网络连接');
        });
}

// 编辑实体
function editEntity(entity) {
    // 将properties字符串转换为属性列表对象数组
    let propertiesList = [];
    if (entity.properties) {
        try {
            // 尝试解析JSON字符串
            propertiesList = JSON.parse(entity.properties);
        } catch (e) {
            // 如果解析失败，创建一个空数组
            propertiesList = [];
        }
    }

    currentEntity.value = {
        ...entity,
        propertiesList: Array.isArray(propertiesList) ? propertiesList : []
    };
    dialogVisible.value = true;
}

// 修改实体类
function saveEntity() {
    const index = entities.value.findIndex(e => e.id === currentEntity.value.id);
    if (index !== -1) {
        // 将属性列表转换为JSON字符串保存
        const entityToSave = { ...currentEntity.value };
        entityToSave.properties = JSON.stringify(currentEntity.value.propertiesList);
        entities.value[index] = entityToSave;
        dialogVisible.value = false;

        // 更新 store 中的实体类数据
        editorStore.updateEntityClass(entityToSave);

        // 从 editorStore 获取文档 ID
        const documentId = editorStore.documentInfo?.id;

        if (!documentId) {
            ElMessage.success('实体编辑已保存，但未能同步到数据库（未找到文档ID）');
            return;
        }

        // 准备保存到数据库的实体数据
        const entityClassToSave = {
            docu_id: documentId,
            id: entityToSave.id,
            name: entityToSave.text,
            description: entityToSave.description,
            path: entityToSave.path,
            attribute: entityToSave.properties
        };

        // 显示加载提示
        const loadingEntityClass = ElLoading.service({ fullscreen: true, text: '正在同步实体类到数据库...' });

        // 发送请求到后端保存实体类
        axios.put('/update_entity_class', {
            entityClasses: entityClassToSave
        })
            .then(response => {
                loadingEntityClass.close();
                if (response.data.code === 200) {
                    // 数据库更新成功后，重新从数据库加载实体类数据
                    loadEntitiesFromDatabase();
                    ElMessage.success('实体编辑已保存并同步到数据库');
                } else {
                    ElMessage.warning(`实体编辑同步到数据库失败: ${response.data.message || '未知错误'}`);
                }
            })
            .catch(error => {
                loadingEntityClass.close();
                console.error('同步实体类到数据库时出错:', error);
                ElMessage.warning('实体编辑已保存，但同步到数据库失败，请检查网络连接');
            });
    }
}

// 删除实体
function deleteEntity(entity) {
    entityToDelete.value = entity;
    deleteDialogVisible.value = true;
}

// 修改删除实体类的方法
function confirmDelete() {
    if (entityToDelete.value) {
        const index = entities.value.findIndex(e => e.id === entityToDelete.value.id);
        if (index !== -1) {
            const deletedEntityId = entityToDelete.value.id;
            entities.value.splice(index, 1);
            // 从 store 中删除实体类
            editorStore.deleteEntityClass(deletedEntityId);
            // 从 store 中删除该实体类的所有实例
            editorStore.deleteEntityInstancesByEntityId(deletedEntityId);

            // 从 editorStore 获取文档 ID
            const documentId = editorStore.documentInfo?.id;

            if (!documentId) {
                ElMessage.success('实体已删除，但未能同步到数据库（未找到文档ID）');
                deleteDialogVisible.value = false;
                entityToDelete.value = null;
                return;
            }

            // 显示加载提示
            const loadingEntityClass = ElLoading.service({ fullscreen: true, text: '正在从数据库删除实体类...' });

            // 发送请求到后端删除实体类
            axios.post('/delete_entity_class', {
                documentId: documentId,
                entityId: deletedEntityId
            })
                .then(response => {
                    loadingEntityClass.close();
                    if (response.data.code === 200) {
                        ElMessage.success('实体已成功删除并从数据库中移除');

                        // 同时删除与该实体类关联的所有实体实例
                        axios.post('/delete_entity_instances_by_entity_id', {
                            documentId: documentId,
                            entityId: deletedEntityId
                        })
                            .then(instanceResponse => {
                                if (instanceResponse.data.code === 200) {
                                    console.log('成功从数据库删除相关实体实例');
                                } else {
                                    console.warn('从数据库删除实体实例失败:', instanceResponse.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('删除实体实例请求失败:', error);
                            });
                    } else {
                        ElMessage.warning(`实体已删除，但从数据库删除失败: ${response.data.message || '未知错误'}`);
                    }
                    deleteDialogVisible.value = false;
                    entityToDelete.value = null;
                })
                .catch(error => {
                    loadingEntityClass.close();
                    console.error('从数据库删除实体类时出错:', error);
                    ElMessage.warning('实体已删除，但从数据库删除失败，请检查网络连接');
                    deleteDialogVisible.value = false;
                    entityToDelete.value = null;
                });
            return;
        }
        deleteDialogVisible.value = false;
        entityToDelete.value = null;
    }
}

// 添加属性
function addProperty() {
    currentEntity.value.propertiesList.push({
        key: '',
        type: 'text',
        description: ''
    });
}

// 删除属性
function removeProperty(index) {
    currentEntity.value.propertiesList.splice(index, 1);
}

// 导出实体定义
function exportDefinition() {
    if (entities.value.length === 0) {
        ElMessage.error('没有可导出的实体数据');
        return;
    }

    // 准备导出数据
    const exportData = entities.value.map(entity => ({
        id: entity.id,
        text: entity.text,
        description: entity.description,
        path: entity.path,
        properties: entity.properties
    }));

    // 询问用户是否同时保存到数据库
    ElMessageBox.confirm('是否同时将实体类保存到数据库？', '导出确认', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'info'
    }).then(() => {
        // 用户点击了"是"，准备保存到数据库
        const documentId = editorStore.documentInfo?.id;

        if (!documentId) {
            ElMessage.warning('未能获取到文档ID，无法保存到数据库');
            // 仍然导出文件
            exportToExcel(exportData);
            return;
        }

        // 显示加载提示
        const loadingEntityClass = ElLoading.service({ fullscreen: true, text: '正在保存实体类到数据库...' });

        // 发送请求到后端保存实体类
        axios.post('/import_entity_class', {
            documentId: documentId,
            entityClasses: exportData
        })
            .then(response => {
                loadingEntityClass.close();
                if (response.data.code === 200) {
                    ElMessage.success('实体类已成功保存到数据库');
                    // 导出文件
                    exportToExcel(exportData);
                } else {
                    ElMessage.warning(`保存到数据库失败: ${response.data.message || '未知错误'}`);
                    // 仍然导出文件
                    exportToExcel(exportData);
                }
            })
            .catch(error => {
                loadingEntityClass.close();
                console.error('保存实体类到数据库时出错:', error);
                ElMessage.warning('保存到数据库失败，请检查网络连接');
                // 仍然导出文件
                exportToExcel(exportData);
            });
    }).catch(() => {
        // 用户点击了"否"，只导出文件不保存到数据库
        exportToExcel(exportData);
    });
}

// 将实体数据导出为Excel文件
function exportToExcel(exportData) {
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(exportData);
    XLSX.utils.book_append_sheet(wb, ws, '实体定义');

    // 生成Excel文件并下载
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '实体定义.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
}

// 导入定义
function triggerFileUpload() {
    fileInput.value.click();
}

// 下载样例定义
function downloadSampleDefinition() {
    // 创建样例实体数据
    const sampleEntities = [
        {
            id: 'person',
            text: '人物',
            description: '指人物实体',
            path: '/entities/person',
            properties: JSON.stringify([
                { key: 'name', type: 'text', description: '姓名' },
                { key: 'age', type: 'number', description: '年龄' },
                { key: 'gender', type: 'text', description: '性别' }
            ])
        },
        {
            id: 'location',
            text: '地点',
            description: '指地理位置实体',
            path: '/entities/location',
            properties: JSON.stringify([
                { key: 'name', type: 'text', description: '地名' },
                { key: 'coordinates', type: 'text', description: '坐标' },
                { key: 'country', type: 'text', description: '所属国家' }
            ])
        },
        {
            id: 'organization',
            text: '组织',
            description: '指组织机构实体',
            path: '/entities/organization',
            properties: JSON.stringify([
                { key: 'name', type: 'text', description: '组织名称' },
                { key: 'type', type: 'text', description: '组织类型' },
                { key: 'founded', type: 'text', description: '成立日期' }
            ])
        }
    ];

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(sampleEntities);

    // 设置列宽
    const wscols = [
        { wch: 15 }, // id
        { wch: 15 }, // text
        { wch: 25 }, // description
        { wch: 20 }, // path
        { wch: 50 } // properties
    ];
    ws['!cols'] = wscols;

    XLSX.utils.book_append_sheet(wb, ws, '实体类定义样例');

    // 生成Excel文件并下载
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '实体类定义样例.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('样例定义已下载');
}

// 实体类定义文件上传
function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) {
        ElMessage.error('请选择文件');
        return;
    }

    // 验证文件类型
    if (!file.name.endsWith('.xlsx')) {
        ElMessage.error('请上传.xlsx格式的文件');
        return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
        try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });

            if (workbook.SheetNames.length === 0) {
                throw new Error('Excel文件中没有工作表');
            }

            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            console.log("worksheet:", worksheet)
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            console.log("jsonData:", jsonData)

            if (jsonData.length === 0) {
                throw new Error('Excel文件中没有数据');
            }

            // 验证数据格式
            const validData = jsonData.filter(row => {
                const hasRequiredFields = row['id'] && row['text'] && row['description'] && row['path'] && row['properties'];
                console.log('hasRequiredFields', hasRequiredFields)
                return hasRequiredFields;
            });

            if (validData.length === 0) {
                throw new Error('没有找到有效的实体数据，请确保Excel中包含必要的字段');
            }

            // 转换数据格式并添加已存储或新生成的背景色
            const formattedEntities = validData.map(row => {
                // 使用editorStore获取或生成颜色
                const backgroundColor = editorStore.getEntityColor(row['id']);

                return {
                    id: row['id'],
                    text: row['text'],
                    description: row['description'],
                    path: row['path'],
                    properties: row['properties'],
                    style: { 'background-color': backgroundColor }
                };
            });

            entities.value = formattedEntities;
            // 更新全局实体列表，供TinyMCE编辑器使用
            window.entities = entities.value;
            // 从 editorStore 获取文档 ID
            const documentId = editorStore.documentInfo?.id;
            // 准备发送到后端的数据
            const entityClassesToSave = entities.value.map(entity => ({
                id: entity.id,
                name: entity.text,
                description: entity.description,
                path: entity.path,
                attribute: entity.properties,
                docu_id: documentId
            }));

            if (!documentId) {
                ElMessage.warning('未能获取到文档ID，实体类已导入到本地，但未保存到数据库');
                return;
            }

            // 显示加载提示
            const loadingEntityClass = ElLoading.service({ fullscreen: true, text: '正在保存实体类到数据库...' });

            // 发送请求到后端保存实体类
            axios.post('/import_entity_class', {
                entityClasses: entityClassesToSave
            })
                .then(response => {
                    loadingEntityClass.close();
                    if (response.data.code === 200) {
                        ElMessage.success(`成功导入并保存 ${entities.value.length} 个实体类到数据库`);
                    } else {
                        ElMessage.warning(`实体类已导入到本地，但保存到数据库失败: ${response.data.message || '未知错误'}`);
                    }
                })
                .catch(error => {
                    loadingEntityClass.close();
                    console.error('保存实体类到数据库时出错:', error);
                    ElMessage.warning('实体类已导入到本地，但保存到数据库失败，请检查网络连接');
                });
        } catch (error) {
            console.error('文件解析错误:', error);
            ElMessage.error(error.message || '文件解析失败，请检查文件格式');
        }
    };

    reader.onerror = () => {
        ElMessage.error('文件读取失败');
    };

    reader.readAsArrayBuffer(file);
}

// 监听标注更新
watch(() => editorStore.entityInstancesLastUpdated, () => {
    console.log("检测到实体实例数据更新，即将重新加载实例数据和更新标记数量");
    debouncedLoadInstances();
    // 强制立即更新实体标记数量，不使用防抖
    updateEntityMarkedCount();
});
</script>

<style scoped>
/* 未检查状态的实体实例标识 */
/*.unchecked-indicator {
    position: absolute;
    top: 2px;
    right: 2px;
    width: 6px;
    height: 6px;
    background-color: red;
    border-radius: 50%;
}*/

.left-menu {
    display: flex;
    flex-direction: column;
    width: 290px;
    height: 627px;
    background-color: #f2f1f1;
    margin: 20px;
}

.entity-types {
    padding: 10px;
    display: flex;
    flex-direction: column;
    height: 250px;
    margin-bottom: 10px;
    background-color: #ffffff;
    border-radius: 10px;
}

.entity-instances {
    display: flex;
    flex-direction: column;
    height: 500px;
    background-color: #ffffff;
    margin-top: 10px;
    border-radius: 10px;
    padding: 10px;
    overflow-y: auto;
    /* 添加垂直滚动条 */
}

.head-img {
    margin-bottom: 10px;
    display: flex;
    /* 使用 flexbox 布局 */
    align-items: center;
}

.head-img div {
    margin-left: 5px;
}

.button {
    display: flex;
    /* 使用 flexbox 布局 */
    gap: 10px;
    /* 设置按钮之间的间距 */
}

.button button {
    font-size: small;
    width: 100px;
}

.entity-type-list {
    height: 150px;
    /* 设置固定高度 */
    overflow-y: auto;
    /* 启用垂直滚动 */
    margin: 5px 0;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.entity-type-item {
    margin: 5px 0;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.entity-info {
    flex-grow: 1;
}

.entity-description {
    font-size: 0.9em;
    color: #666;
    margin-top: 4px;
}

.entity-path {
    font-size: 0.8em;
    color: #888;
    margin-top: 2px;
}

.entity-properties {
    font-size: 0.8em;
    color: #888;
    margin-top: 2px;
}

.entity-marked-count {
    display: inline-block;
    background-color: #409eff;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 0.8em;
    margin-left: 5px;
}

.entity-actions {
    display: flex;
    gap: 5px;
}

.dialog {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.dialog-content {
    background-color: #fff;
    padding: 0;
    border-radius: 8px;
    width: 800px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-content h3 {
    margin: 0;
    margin-left: 10px;
    padding: 15px 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #ffffff;
    font-size: 16px;
    color: #333;
    text-align: left;
}

.dialog-content label {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    border-bottom: 1px solid #f0f0f0;
}

.dialog-content label:last-of-type {
    border-bottom: none;
}

.dialog-content label input {
    flex: 1;
    margin-left: 10px;
    padding: 8px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
}

.dialog-content label input:disabled {
    background-color: #ffffff;
    cursor: not-allowed;
}

.attribute-button {
    background-color: #fff;
    color: #409eff;
    border: 1px solid #409eff;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 5px;
    margin-bottom: 0;
    display: block;
}

.attribute-button:hover {
    background-color: #ecf5ff;
}

.property-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    gap: 8px;
}

.property-item input,
.property-item select {
    padding: 6px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.property-item input {
    flex: 1;
}

.property-item select {
    width: 100px;
}

.remove-button {
    background-color: #f56c6c;
    color: white;
    border: none;
    padding: 6px 10px;
    border-radius: 4px;
    cursor: pointer;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px;
    background-color: #ffffff;
    border-top: 1px solid #ffffff;
}

.dialog-footer button {
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.dialog-footer button:first-child {
    background-color: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
}

.dialog-footer button:last-child {
    background-color: #409eff;
    border: 1px solid #409eff;
    color: #fff;
}

.dialog-content-delete {
    background-color: #ffffff;
    padding: 0;
    border-radius: 8px;
    width: 400px;
    box-shadow: 0 2px 12px rgba(255, 255, 255, 0.1);
}

.dialog-content-delete h3 {
    margin: 0;
    margin-left: 10px;
    padding: 15px 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #fffefe;
    font-size: 16px;
    color: #333;
    text-align: left;
}

.entity-instance-container {
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.entity-instance-title {
    font-weight: bold;
    margin-bottom: 8px;
    font-size: 14px;
}

.entity-instance-boxes {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 5px;
    max-height: 120px;
    /* 限制高度 */
    overflow-y: auto;
    /* 启用垂直滚动 */
    padding: 5px;
    border-radius: 4px;
    background-color: #f9f9f9;
}

.entity-instance-item {
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    display: inline-block;
    margin-right: 5px;
    margin-bottom: 5px;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    position: relative;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.entity-instance-content {
    font-size: 12px;
}

.entity-check-status {
    font-size: 10px;
    margin-top: 4px;
    text-align: right;
    color: #666;
}

.unchecked-indicator {
    position: absolute;
    top: 2px;
    right: 2px;
    width: 6px;
    height: 6px;
    background-color: red;
    border-radius: 50%;
    box-shadow: 0 0 2px rgba(0, 0, 0, 0.3);
}

.empty-instance {
    opacity: 0.6;
    font-style: italic;
}

.entity-instance-status {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}
</style>
